package edu.gdut.tiantian.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import edu.gdut.tiantian.entity.CartItem;
import edu.gdut.tiantian.service.Impl.CartService;

@Controller
@RequestMapping("/cart")
public class CartController {
	@Autowired
	private CartService cartService;

	@RequestMapping("/delCartItem.do")
	public String delCartItem(Integer cartItemId, String userId) {
		cartService.delCartItem(cartItemId);
		return "redirect:/cart/getMyCart.do?userId=" + userId;
	}

	@RequestMapping("/clearCart.do")
	public String clearCart(String userId) {
		cartService.clearCart(userId);
		return "redirect:/cart/getMyCart.do?userId=" + userId;
	}

	@RequestMapping("/getMyCart.do")
	public ModelAndView getMyCart(String userId, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView();
		List<CartItem> cartItems = cartService.getCart(userId);
		if (cartItems.size() == 0 || cartItems == null)
			mv.addObject("cartMsg", "购物车为空，赶快去浏览商品吧！");
		float totalMoney = 0f;
		for(CartItem cart : cartItems) {
			totalMoney += cart.getProduct().getPrice() * cart.getBuyNum();
		}
		req.getSession().setAttribute("cartItems", cartItems);
		mv.addObject("cartTotal",totalMoney);
		mv.setViewName("user/myCart");
		return mv;
	}

	@RequestMapping("/addProductToCart.do")
	public String addProductToCart(String userId, String productId, Integer buyNum) {
		CartItem cartItem = cartService.findById(userId, productId);
		if (cartItem == null) {
			cartService.addProductToCart(userId, productId, buyNum);
		} else {
			cartService.updateCateItem(userId, productId, buyNum+cartItem.getBuyNum());
		}
		return "redirect:/cart/getMyCart.do?userId=" + userId;
	}
}
